package com.jw.blog.shiro.handlers;

import com.jw.blog.wblog.entity.custom.ResultBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author wan Email-wlf18726994755@163.com
 * @version 1.0
 * @date 2020/7/4 12:24
 **/
@RestController
public class ShiroHandler {


    @GetMapping("/unauthorized")
    public ResultBean<Object> unauthorized(){
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(300);
        resultBean.setMsg("对不起没有权限");
        return resultBean;
    }

    @PostMapping("/login")
    public ResultBean<Object> login(@RequestParam(value = "username") String username,
                            @RequestParam(value = "password") String password,
                            @RequestParam(value = "remember",required = false) Boolean remember) {

        Subject subject = SecurityUtils.getSubject();

        if (!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //实现记住我的细节。
            if (remember) {
                token.setRememberMe(true);
            }else {
                token.setRememberMe(false);
            }
            try {
                System.out.println(token.hashCode());
                subject.login(token);

            } catch (IncorrectCredentialsException ae) {
                ResultBean<Object> resultBean = new ResultBean<>();
                resultBean.setCode(ResultBean.FAIL);
                resultBean.setMsg("密码不正确");
                return resultBean;
            } catch (AuthenticationException ae) {
                ResultBean<Object> resultBean = new ResultBean<>();
                resultBean.setCode(ResultBean.FAIL);
                resultBean.setMsg("帐号不存在");
                return resultBean;
            }
        }

        /**
         * 判断是否已经登录
         */
        if (subject.getPrincipal() != null) {
            return new ResultBean<>();
        }
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(403);
        resultBean.setMsg("还未登录");
        return resultBean;
    }
}
